package com.tengju.bff.application.wx;

import com.tengju.bff.application.shared.SkipMessageException;
import com.tengju.data.domain.model.user.StarLevelEnum;
import com.tengju.data.domain.model.user.UserIdCode;
import com.tengju.data.domain.model.wx.WxUserInfo;
import com.tengju.data.domain.model.wx.WxUserInfoRepository;
import com.tengju.support.domain.model.wx.WechatGradeRepository;
import com.tengju.user.domain.model.csm.dealer.CrmDealerInfo;
import com.tengju.user.domain.model.csm.dealer.CrmDealerInfoRepository;
import com.tengju.user.domain.model.user.UserInfo;
import com.tengju.user.domain.service.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static com.google.common.collect.Lists.newArrayList;

/**
 * 升级为经销商后添加到企业微信
 */
@Service
@Slf4j
public class WxUserGradeService {
    private final CrmDealerInfoRepository crmDealerInfoRepository;
    private final WxUserInfoRepository wxUserInfoRepository;
    private final RemoteUserService remoteUserService;
    private final WxUserManageService wxUserManageService;
    private final WechatGradeRepository wechatGradeRepository;

    public WxUserGradeService(CrmDealerInfoRepository crmDealerInfoRepository,
                              WxUserInfoRepository wxUserInfoRepository,
                              RemoteUserService remoteUserService,
                              WxUserManageService wxUserManageService,
                              WechatGradeRepository wechatGradeRepository) {
        this.crmDealerInfoRepository = crmDealerInfoRepository;
        this.wxUserInfoRepository = wxUserInfoRepository;
        this.remoteUserService = remoteUserService;
        this.wxUserManageService = wxUserManageService;
        this.wechatGradeRepository = wechatGradeRepository;
    }

    /**
     * 为升级为经销商的用户添加企业微信
     *
     * @param idCode       升级用户id
     * @param parentIdCode 上级用户id
     */
    public void dealerWechatCreate(long idCode, String businessId) {
        //幂等处理
        if (wechatGradeRepository.businessIdExist(businessId)) {
            log.warn("消息 businessId:{} 已存在，idCode:{}", businessId, idCode);
            return;
        }

        //如果已经处理过部门，则不再处理
        WxUserInfo wxUserInfo = wxUserInfoRepository.selectByIdCode(UserIdCode.of(idCode));
        if (Objects.nonNull(wxUserInfo)) {
            log.warn("用户已经处理过企微，不再处理,idCode:{}", idCode);
            return;
        }
        long rootIdCode = getRootIdCode(idCode);
        if (rootIdCode <= 0) {
            log.error("用户直属团队id不存在,idCode:{}", idCode);
            throw new SkipMessageException("用户直属团队id不存在");
        }
        List<UserInfo> onlyUserByIdList =
                remoteUserService.getOnlyUserByIdList(newArrayList(com.tengju.user.domain.model.user.UserIdCode.of(idCode)));
        if (CollectionUtils.isEmpty(onlyUserByIdList)) {
            log.error("用户信息不存在,idCode:{}", idCode);
            throw new SkipMessageException("用户信息不存在");
        }
        UserInfo userInfo = onlyUserByIdList.get(0);
        if (StringUtils.isBlank(userInfo.getMobile())) {
            log.error("用户手机号不存在，创建企业微信失败,idCode:{}", userInfo.getIdCode().getValue());
            throw new SkipMessageException("用户手机号不存在");
        }
        try {
            wxUserManageService.createUserDepartment(WxUserInfo.of(idCode,
                            rootIdCode,
                            rootIdCode,
                            0,
                            null,
                            StarLevelEnum.NONE,
                            Collections.emptyList()),
                    CrmDealerInfo.of(idCode, userInfo.getName(), userInfo.getMobile())

            );
            wechatGradeRepository.setBusinessId(businessId);
        } catch (Throwable e) {
            log.error("创建企业微信异常,idCode:{},exception:{}", idCode, e.getMessage(), e);
            throw new SkipMessageException("创建企业微信异常");
        }
    }


    /**
     * 实时升级的用户 关系表中可能不存在数据，所以通过递归查找用户的上级在关系表中的数据来查找sec
     *
     * @param idCode       当前用户id
     * @param parentIdCode 父id
     * @return 根用户id
     */
    public long getRootIdCode(long idCode) {
        if (idCode == 0) {
            return idCode;
        }
        UserInfo userInfo = remoteUserService.getOnlyParentUserByIdList(idCode);
        //如果上级id不存在，说明是根用户
        if (Objects.isNull(userInfo.getPidCode())) {
            return idCode;
        }

        //查询当前大数据同步的库中是否有信息
        CrmDealerInfo crmDealerSupInfo =
                crmDealerInfoRepository.getCrmDealerSupInfo(
                        com.tengju.user.domain.model.user.UserIdCode.of(userInfo.getPidCode().getValue()));
        if (Objects.nonNull(crmDealerSupInfo)) {
            return getRootId(crmDealerSupInfo);
        }
        //查询该用户上级 做递归处理
        UserInfo parentUserInfo = remoteUserService.getOnlyParentUserByIdList(userInfo.getPidCode().getValue());
        //如果上级id不存在，说明是根用户
        if (Objects.isNull(parentUserInfo.getPidCode())) {
            return parentUserInfo.getIdCode().getValue();
        }
        return getRootIdCode(userInfo.getPidCode().getValue());
    }

    private long getRootId(CrmDealerInfo crmDealerInfo) {
        //从sec开始 找到第一个不为0的值作为根id
        if (Objects.nonNull(crmDealerInfo.getBlSecIdCode()) && crmDealerInfo.getBlSecIdCode() > 0) {
            return crmDealerInfo.getBlSecIdCode();
        } else if (Objects.nonNull(crmDealerInfo.getBlEcIdCode()) && crmDealerInfo.getBlEcIdCode() > 0) {
            return crmDealerInfo.getBlEcIdCode();
        } else if (Objects.nonNull(crmDealerInfo.getBlStar4IdCode()) && crmDealerInfo.getBlStar4IdCode() > 0) {
            return crmDealerInfo.getBlStar4IdCode();
        } else if (Objects.nonNull(crmDealerInfo.getBlStar3IdCode()) && crmDealerInfo.getBlStar3IdCode() > 0) {
            return crmDealerInfo.getBlStar3IdCode();
        } else if (Objects.nonNull(crmDealerInfo.getBlStar2IdCode()) && crmDealerInfo.getBlStar2IdCode() > 0) {
            return crmDealerInfo.getBlStar2IdCode();
        } else if (Objects.nonNull(crmDealerInfo.getBlStar1IdCode()) && crmDealerInfo.getBlStar1IdCode() > 0) {
            return crmDealerInfo.getBlStar1IdCode();
        }
        return 0L;

    }


}
